package com.cpit.platform.security.handler;

import com.cpit.platform.common.constant.LogConstant;
import com.cpit.platform.common.entity.Result;
import com.cpit.platform.common.utils.LogUtils;
import com.cpit.platform.dto.OperLog;
import com.cpit.platform.service.OperLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private OperLogService operLogService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

        String name = request.getParameter("username");
        String password = request.getParameter("password");

        OperLog operLog = LogUtils.createOperLog(LogConstant.MODULE_SECURITY, LogConstant.OPER_LOGIN,
                Result.CODE_FAILED, name, name);
        operLogService.writeLog(operLog);

        request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", exception);
        request.getRequestDispatcher("/").forward(request, response);
    }

}